package com.chinairi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinairi.common.annotation.DoPage;
import com.chinairi.common.model.ApprovalModel;
import com.chinairi.common.utils.IdGenerator;
import com.chinairi.common.utils.RedisUtil;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.controller.viewobject.UserRoleRelationVo;
import com.chinairi.mall.dao.UserCompanyRelaMapper;
import com.chinairi.mall.dao.UserCompanyTypeMapper;
import com.chinairi.mall.enums.RoleIdType;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.model.UserCompanyInfo;
import com.chinairi.mall.dao.UserCompanyInfoMapper;
import com.chinairi.mall.model.UserCompanyRela;
import com.chinairi.mall.model.UserCompanyType;
import com.chinairi.mall.service.IUserCompanyInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.mall.service.modelobject.AdminInfoMapMO;
import com.chinairi.mall.service.modelobject.CompanyTypeMO;
import com.chinairi.mall.service.modelobject.ShopInfoToCompRedisMO;
import com.chinairi.mall.service.modelobject.UserInfoToRedisMO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 用户企业信息表 服务实现类
 * </p>
 *
 * @author Webgasd
 * @since 2020-09-16
 */
@Service
public class UserCompanyInfoServiceImpl extends ServiceImpl<UserCompanyInfoMapper, UserCompanyInfo> implements IUserCompanyInfoService {

    @Autowired
    private UserCompanyInfoMapper userCompanyInfoMapper;
    @Autowired
    private UserCompanyTypeMapper userCompanyTypeMapper;
    @Autowired
    private UserCompanyTypeServiceImpl userCompanyTypeService;
    @Autowired
    private UserCompanyRelaMapper userCompanyRelaMapper;
    @Autowired
    private RedisUtil redisUtil;

    public void putRedis() {
        redisUtil.del("compMap");
        List<UserCompanyInfo> userCompanyInfoList = userCompanyInfoMapper.getIdAndName();
        if (userCompanyInfoList.size() > 0) {
            Map<String, Object> compMap = new HashMap<>(userCompanyInfoList.size());
            for (UserCompanyInfo userCompanyInfo : userCompanyInfoList) {
                compMap.put(userCompanyInfo.getUciDbid(), userCompanyInfo.getUciCompName());
            }
            redisUtil.hmset("compMap", compMap, 3700);
        }

    }

    public void putAdminInfoToRedis() {
        redisUtil.del("adminInfoMap");
        AdminInfoMapMO adminInfoMapMo = userCompanyInfoMapper.getAdminInfo();
        Map<String, Object> shopInfoToCompMap = new HashMap<>(1);
        shopInfoToCompMap.put("uciDbid", adminInfoMapMo.getUciDbid());
        shopInfoToCompMap.put("uciCompName", adminInfoMapMo.getUciCompName());
        shopInfoToCompMap.put("uciCompCharacter", adminInfoMapMo.getUciCompCharacter());
        shopInfoToCompMap.put("csDbid0", adminInfoMapMo.getCsDbid0());
        shopInfoToCompMap.put("csShopName0", adminInfoMapMo.getCsShopName0());
        shopInfoToCompMap.put("csDbid1", adminInfoMapMo.getCsDbid1());
        shopInfoToCompMap.put("csShopName1", adminInfoMapMo.getCsShopName1());
        shopInfoToCompMap.put("csDbid2", adminInfoMapMo.getCsDbid2());
        shopInfoToCompMap.put("csShopName2", adminInfoMapMo.getCsShopName2());
        shopInfoToCompMap.put("csDbid3", adminInfoMapMo.getCsDbid3());
        shopInfoToCompMap.put("csShopName3", adminInfoMapMo.getCsShopName3());
        shopInfoToCompMap.put("csDbid4", adminInfoMapMo.getCsDbid4());
        shopInfoToCompMap.put("csShopName4", adminInfoMapMo.getCsShopName4());
        shopInfoToCompMap.put("csDbid5", adminInfoMapMo.getCsDbid5());
        shopInfoToCompMap.put("csShopName5", adminInfoMapMo.getCsShopName5());
        shopInfoToCompMap.put("csDbid6", adminInfoMapMo.getCsDbid6());
        shopInfoToCompMap.put("csShopName6", adminInfoMapMo.getCsShopName6());
        redisUtil.hmset("adminInfoMap", shopInfoToCompMap, 86500);
    }

    public Map<Object, Object> getAdminInfoFromRedis() {
        Map<Object, Object> compMapResult = redisUtil.hmget("adminInfoMap");
        if (!redisUtil.hasKey("adminInfoMap") || compMapResult.size() == 0 || compMapResult.get("uciDbid") == null) {
            putAdminInfoToRedis();
        }
        return redisUtil.hmget("adminInfoMap");
    }

    public Object getCompMapFromRedis(String uciDbId) {
        Map<Object, Object> compMap = redisUtil.hmget("compMap");
        if (!redisUtil.hasKey("compMap") || compMap.size() == 0 || compMap.get(uciDbId) == null) {
            putRedis();
        }
        return redisUtil.hmget("compMap").get(uciDbId);
    }

    /**
     * 店铺id获取企业信息
     */
    public void putShopInfoToRedis() {
        redisUtil.del("shopInfoMap");
        List<ShopInfoToCompRedisMO> shopInfoToCompRedisMoList = userCompanyInfoMapper.getShopInfoToComp();
        if (shopInfoToCompRedisMoList.size() > 0) {
            Map<String, Object> shopInfoMap = new HashMap<>(shopInfoToCompRedisMoList.size());
            for (ShopInfoToCompRedisMO shopInfoToCompRedisMo : shopInfoToCompRedisMoList) {
                shopInfoMap.put(shopInfoToCompRedisMo.getCsDbid(), shopInfoToCompRedisMo);
            }
            redisUtil.hmset("shopInfoMap", shopInfoMap, 86500);
        }
    }

    /**
     * 获取店铺和企业信息redis
     *
     * @param csDbID
     * @return
     */
    public ShopInfoToCompRedisMO getShopInfoToCompFromRedis(String csDbID) {
        Map<Object, Object> shopInfoMap = redisUtil.hmget("shopInfoMap");
        if (!redisUtil.hasKey("shopInfoMap") || shopInfoMap.size() == 0 || shopInfoMap.get(csDbID) == null) {
            putShopInfoToRedis();
        }
        return (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(csDbID);
    }

    /**
     * 插入企业信息+用户关系+资质信息。
     *
     * @param userCompanyInfo
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<UserCompanyType> add(UserCompanyInfo userCompanyInfo, String userId) {
        String before = userCompanyInfo.getUciDbid();
        if (before == null || "".equals(before)) {
            userCompanyInfo.setUciDbid(UUID.randomUUID().toString().replace("-", ""));
        }
        String name = userCompanyTypeService.transformIdToName(userCompanyInfo.getUciCompTypeInt());
        userCompanyInfo.setUciCompTypeName(name);
        userCompanyInfo.setUciCompCharacter(0);
        userCompanyInfo.setCreateUser(UserSession.getUserId());
        userCompanyInfo.setCreateTime(new Date());
        UserCompanyType userCompanyType = new UserCompanyType();
        userCompanyType.setId(userCompanyInfo.getUciDbid());
        String now = userCompanyType.getId();
        userCompanyType.setCompanyTypeInt(userCompanyInfo.getUciCompTypeInt());
        userCompanyType.setCompanyTypeName(name);
            /*
            提交审批流
             */
        //addFlowable(userCompanyInfo.getUciDbid(), userId);
            /*
            默认值：0未审核
            成功后继续进行下边步骤
            修改审批状态为0-审批中
            */
        userCompanyType.setStatus(0);
        if (before == null || "".equals(before)) {
            userCompanyInfoMapper.insert(userCompanyInfo);
        } else {
            userCompanyInfoMapper.updateById(userCompanyInfo);
        }
        /*
        删除当前的id+类型的原有数据，再添加新的待审批数据。
         */
        QueryWrapper<UserCompanyType> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(true, "COMPANY_TYPE_INT", userCompanyType.getCompanyTypeInt())
                .eq(StringUtils.isNotEmpty(userCompanyType.getId()), "ID", userCompanyType.getId());
        userCompanyTypeMapper.delete(queryWrapper);
        userCompanyTypeMapper.insert(userCompanyType);
        if (before == null || "".equals(before)) {
            //绑定用户和企业信息表
            UserCompanyRela userCompanyRela = new UserCompanyRela();
            userCompanyRela.setCuDbid(UUID.randomUUID().toString().replace("-", ""));
            userCompanyRela.setUciDbid(userCompanyInfo.getUciDbid());
            userCompanyRela.setUserId(userId);
            userCompanyRelaMapper.insert(userCompanyRela);
        }
        putRedis();
        return userCompanyTypeMapper.getComTypeIntList(now);
    }

    /**
     * 更新企业信息
     *
     * @param userCompanyInfo
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserCompanyInfo userCompanyInfo, String userId) {
        if (userCompanyInfo.getUciDbid() == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "传入数据为空");
        }
        userCompanyInfoMapper.updateById(userCompanyInfo);
        putRedis();
    }

    /**
     * 审批流状态更改接口
     *
     * @param approvalModel
     */
    @Override
    public void updateFlowable(ApprovalModel approvalModel) {
        UserCompanyInfo userCompanyInfo = new UserCompanyInfo();
        userCompanyInfo.setUciDbid(approvalModel.getId());
        userCompanyInfo.setUciApproveOpinion(approvalModel.getApprovalOpinion());
        int status = 0;
        if ("01".equals(approvalModel.getApprovalStatus())) {
            status = 1;
        } else if ("02".equals(approvalModel.getApprovalStatus())) {
            status = 2;
        }
        userCompanyInfo.setUciApproveState(status);
        userCompanyInfoMapper.updateById(userCompanyInfo);
    }

    /**
     * 根据用户id查询绑定的企业
     *
     * @return
     */
    @Override
    public CompanyTypeMO getCom(Integer type) {
        String userId = UserSession.getUserId();
        if (userId == null || "".equals(userId)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "用户id为空");
        }
        CompanyTypeMO companyTypeMo = userCompanyInfoMapper.getByUserId(userId);
        if (companyTypeMo == null) {
            throw new BusinessException(EmBusinessError.STUDENT_NOT_EXIST, "未绑定企业");
        }
        if (type != null) {
            QueryWrapper<UserCompanyType> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq(true, "COMPANY_TYPE_INT", type)
                    .eq(StringUtils.isNotEmpty(companyTypeMo.getUciDbid()), "ID", companyTypeMo.getUciDbid());
            UserCompanyType result = userCompanyTypeMapper.selectOne(queryWrapper);
            if (result != null) {
                BeanUtils.copyProperties(result, companyTypeMo);
            }
        }
        return companyTypeMo;
    }

    /**
     * 获取全部企业
     *
     * @return
     */
    @Override
    @DoPage
    public List<CompanyTypeMO> getComList(CompanyTypeMO companyTypeMo) {
        return userCompanyInfoMapper.getComList(companyTypeMo);
    }

    /**
     * 更新企业审核状态
     *
     * @param companyTypeMo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(CompanyTypeMO companyTypeMo) {
        if (companyTypeMo.getId() == null || "".equals(companyTypeMo.getId())) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "审核企业不存在，请检查后重试");
        }
        if (companyTypeMo.getStatus() == null || 2 < companyTypeMo.getStatus()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "审核状态有误，请检查后重试");
        }
        companyTypeMo.setCheckPerson(UserSession.getUserId());
        companyTypeMo.setCheckTime(new Date());
        userCompanyInfoMapper.changeStatus(companyTypeMo);

        //獲取用戶類型對應的角色id
        String roleTypeId = null;
        //獲取該企業下的首個用戶id
        String userId = userCompanyInfoMapper.getByUserIdByCompanyId(companyTypeMo.getId());
        UserRoleRelationVo userRoleRelationVo = new UserRoleRelationVo();
        if ("1".equals(String.valueOf(companyTypeMo.getCompanyTypeInt()))) {
            roleTypeId = userCompanyInfoMapper.getParamValueByParamKey(RoleIdType.GYSGLY_ID.getKey());
            userRoleRelationVo.setUid(IdGenerator.UUID());
            userRoleRelationVo.setRoleId(roleTypeId);
            userRoleRelationVo.setUserId(userId);
            userCompanyInfoMapper.addRoleRelation(userRoleRelationVo);
        } else if ("3".equals(String.valueOf(companyTypeMo.getCompanyTypeInt()))) {
            roleTypeId = userCompanyInfoMapper.getParamValueByParamKey(RoleIdType.CGSGLY_ID.getKey());
            userRoleRelationVo.setUid(IdGenerator.UUID());
            userRoleRelationVo.setRoleId(roleTypeId);
            userRoleRelationVo.setUserId(userId);
            userCompanyInfoMapper.addRoleRelation(userRoleRelationVo);
        }

    }

    /**
     * 限时删除企业资质
     *
     * @param companyTypeMo mo文件
     */
    @Override
    public void deleteStatus(CompanyTypeMO companyTypeMo) {
        if (companyTypeMo.getId() == null || "".equals(companyTypeMo.getId())) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "审核企业不存在，请检查后重试");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startTime = simpleDateFormat.parse(simpleDateFormat.format(companyTypeMo.getDeleteStart()));
            System.out.println(startTime);
            Date endTime = simpleDateFormat.parse(simpleDateFormat.format(companyTypeMo.getDeleteEnd()));
            System.out.println(endTime);
            companyTypeMo.setDeleteStart(startTime);
            companyTypeMo.setDeleteEnd(endTime);
            companyTypeMo.setDeletePerson(UserSession.getUserId());
            userCompanyInfoMapper.deleteStatus(companyTypeMo);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时任务
     */
    @Override
    public void updateStatus() {
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(now);
        System.out.println(nowTime);
        userCompanyInfoMapper.updateStatus(nowTime);
    }

    /**
     * 获取店铺和企业信息
     *
     * @param csDbid
     * @return
     */
    @Override
    public ShopInfoToCompRedisMO getShopInfoAndCompInfo(String csDbid) {
        return userCompanyInfoMapper.getShopInfoAndCompInfo(csDbid);
    }

    @Override
    public List<Map<String, Object>> getBelongToList() {
        return userCompanyInfoMapper.getBelongToList();
    }

}
